﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.Core.SeedData
{
    public class SqlSugarSeedHelper
    {
        public static void RunSeeds(SqlSugarScope db, SeedMode mode)
        {
            // 获取所有种子数据实现
            var seedTypes = Assembly.GetEntryAssembly().GetTypes()
                .Where(t => t.GetInterfaces().Any(i =>
                    i.IsGenericType &&
                    i.GetGenericTypeDefinition() == typeof(ISqlSugarSeed<>)));

            foreach (var seedType in seedTypes)
            {
                var entityType = seedType.GetInterfaces()
                    .First(i => i.GetGenericTypeDefinition() == typeof(ISqlSugarSeed<>))
                    .GetGenericArguments().First();


                // 通过接口约束创建实例
                if (Activator.CreateInstance(seedType) is ISqlSugarSeed seedInstance)
                {
                    if (ShouldExecuteSeed(db, mode, entityType))
                    {
                        seedInstance.Execute(db);
                    }
                }
            }
        }

        private static bool ShouldExecuteSeed(SqlSugarScope db, SeedMode mode, Type entityType)
        {
            return mode switch
            {
                SeedMode.Always => true,
                SeedMode.WhenEmpty => !db.QueryableByObject(entityType).Any(),
                _ => false
            };
        }
    }
}
